'use strict';
var auth = {
    user: '邮箱地址',
    pass: '授权码'
}



// var auth = {
//     user: 'xxx@163.com',
//     pass: 'xxxxxxxxxxxxxxx'
// }


const nodemailer =require('nodemailer');
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
app.use(express.urlencoded({extended: false}));
app.use(express.json());
var PORT = 3000;

var transporter = nodemailer.createTransport({
    // host: 'smtp.ethereal.email',
    service: 'qq',
    // 使用了内置传输发送邮件 查看支持列表：https://nodemailer.com/smtp/well-known/
    port: 465,
    // SMTP 端口
    secureConnection: true,
    // 使用了 SSL
    auth:{
        user:auth.user,
        pass:auth.pass,// 这里密码不是qq密码，是你设置的smtp授权码
    }
});

app.post('/email', (req, res) => {
    var email = req.body.email;
    var code = parseInt(Math.random()*1000000)+"";
    console.log(email)
    var template = '<div style="text-align:center;"><div><b>您的验证码是：</b></div><div><h2>'+code+'</h2></div><div><p>请不要将验证码给其他人</p></div></div>';
    var mailOptions = {
        from:'<同上面的邮箱地址>',
        // sender address
        to: email,
        // list of receivers
        subject:'验证码',
        // 发送text或者html格式
        html:template//'<div><b>验证码是</b></div><div><h2>'+code+'</h2></div>'
    };
    
    // send mail with defined transport object
    transporter.sendMail(mailOptions, (error,info)=>{
        if(error){
            return console.log(error)
        }
        res.send("sent")
        console.log('Message sent: %s', info.messageId);
        // Message sent: <04ec7731-cc68-1ef6-303c-61b0f796b78f@qq.com>
    });
    // res.send("sent")
})

app.post('/getCode', (req, res) => {
    var code = '';
    for(var i = 0; i < 4; i++){
        code += parseInt(Math.random()*1000)%10;
    }
    res.send(code);
})

app.post('/login', (req, res) => {
    console.log(req.body.username)
    console.log(req.body.password)
    var username = req.body.username;
    var password = req.body.password;
    if(username == 'root' && password == 'ok'){
        res.send("success");
    }else{
        res.send("failed");
    }
})

app.listen(PORT, function(err){
	if (err) console.log(err);
	console.log("Server listening on PORT", PORT);
});